package cn.virens.web.components.shiro.spring;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.cache.Cache.ValueWrapper;

import java.util.Collection;
import java.util.Set;

/**
 * Spring 缓存封装对象
 * 
 * @作者 :loioi
 * @创建时间 :2017年7月17日
 */
public class SpringCache<K, V> implements Cache<K, V> {
	private final org.springframework.cache.Cache cache;

	public SpringCache(org.springframework.cache.Cache cache) {
		if (cache == null) throw new IllegalArgumentException("Cache argument cannot be null.");

		this.cache = cache;
	}

	@Override
	@SuppressWarnings("unchecked")
	public V get(K key) throws CacheException {
		if (key == null) return null;
		try {
			ValueWrapper vw = cache.get(key);
			if (vw != null) {
				return (V) vw.get();
			} else {
				return null;
			}
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public V put(K key, V value) throws CacheException {
		if (key == null) return null;
		try {
			V previous = get(key);

			cache.put(key, value);

			return previous;
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public V remove(K key) throws CacheException {
		if (key == null) return null;
		try {
			V previous = get(key);

			cache.evict(key);

			return previous;
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	@Override
	public void clear() throws CacheException {
		cache.clear();
	}

	@Override
	public int size() {
		throw new UnsupportedOperationException("invoke spring cache abstract size method not supported");
	}

	@Override
	public Set<K> keys() {
		throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
	}

	@Override
	public Collection<V> values() {
		throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");
	}

}
